package com.dubbo.service.impl;

import com.alibaba.fastjson.JSON;
import com.dubbo.common.MathUtils;
import com.dubbo.common.ResponseUtil;
import com.dubbo.common.check.CheckUtil;
import com.dubbo.common.number.NumberUtils;
import com.dubbo.common.page.PageResponse;
import com.dubbo.common.page.PageUtils;
import com.dubbo.common.push.JpushClientUtil;
import com.dubbo.domain.*;
import com.dubbo.domain.Process;
import com.dubbo.domain.info.ResultMessage;
import com.dubbo.domain.other.FileInfo;
import com.dubbo.domain.other.ZeroHourFile;
import com.dubbo.mapper.*;
import com.dubbo.mapper.other.FileInfoMapper;
import com.dubbo.mapper.other.ZeroHourFileMapper;
import com.dubbo.service.business.refund.RefundService;
import com.dubbo.service.impl.base.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 退货/换货serviceimp
 * @author chenluqiang
 * @date 2018年12月15日 上午10:08:31 
 *
 */
@Service
@Transactional(readOnly=false,rollbackFor=Exception.class)
public class RefundServiceImpl extends BaseServiceImpl<Refund> implements RefundService {
	
	@Autowired
	private RefundMapper refundMapper;
	@Autowired
	private RefundItemMapper refundItemMapper;
	@Autowired
	private OrderItemMapper orderItemMapper;
	@Autowired
	private OrderMapper orderMapper;
	@Autowired
	private PicMapper picMapper;
	@Autowired
	private FileInfoMapper fileInfoMapper;
	@Autowired
	private RefundPicKeyMapper refundPicKeyMapper;
	@Autowired
	private SRoleLevelMapper sRoleLeveLMapper;
	@Autowired
	private URoleLevelMapper uRoleLevelMapper;
	@Value("${fastdfsUrl}")
	private String fastdfsUrl;
	@Autowired
	private UserMapper userMapper;
	@Autowired 
	private ArticleMapper articleMapper;
	@Autowired
	private RefundShippingMapper  refundShippingMapper;
	@Autowired
	private ProcessMapper processMapper;
	@Autowired
	private ZeroHourFileMapper zeroHourFileMapper;
	@Autowired
	private ORoleLevelMapper oRoleLevelMapper;
	@Autowired
	private CategoryMapper categoryMapper;
	@Autowired
	private CategoryRatioMapper categoryRatioMapper;
	/**
	 * 售后申请页面信息
	 * @author chenluqiang
	 * @date 2018年12月15日 下午4:15:11 
	 * @param orderId 订单id
	 * @param type  申请类型 0=退货 1=换货
	 * @return
	 */
	@Override
	public Map<String, Object> applyAfterSalePage(String orderId, Integer type) {
		//校验订单id
		if(StringUtils.isBlank(orderId)) {
			return ResponseUtil.ajaxCheckError(ResultMessage.ORDERID_ISNULL);
		}
		if(orderId.length()!=32) {
			return ResponseUtil.ajaxCheckError(ResultMessage.ORDERID_ISERROR,"orderId length must be equal 32!");
		}
		//校验订申请类型 
		if(type==null||type<0||type>1) {
			return ResponseUtil.ajaxCheckError(ResultMessage.TYPE_ISERROR);
		}
		//校验订单是否交易完成
		Map<String, Object> processMap = processMapper.findProcessByOrderId(orderId);
		if(processMap==null||processMap.isEmpty()
					||processMap.get("status")==null
					||StringUtils.isBlank(processMap.get("status").toString())
					||!processMap.get("status").toString().equals("11") //订单状态是否是已完成状态
					||!processMap.get("isRefund").toString().equals("1")) {  //是否能申请售后 0=否 1=是
			return ResponseUtil.ajaxCheckError(ResultMessage.ORDER_APPLY_ERROR);
		}
		
		//页面数据结果集
		Map<String, Object> resultMap  = new HashMap<>();
		
		List<Map<String,Object>> result = null;
		//判断退货还是换货
		if(type==0) {
			//根据订单id获取退货信息
			result = orderMapper.getReturnGoodsByOrderId(orderId);
		}else{ 
			//根据订单id获取换货信息
			result = orderMapper.getExchangeGoodsByOrderId(orderId);
		}
		
		//图片处理
		this.handleListPics(result,"goodsPic");
		
		//设置结算总价
		Map<String, Object> check = this.settingSettlementMoney(resultMap,result);
		if(check!=null) {
			return check;
		}
//		result.add(resultMap);
//		return ResponseUtil.ajaxCheckSuccess(ResultMessage.OK,result);
		return ResponseUtil.ajaxCheckSuccess(ResultMessage.OK,resultMap);
	}
	
	/**
	 * 生成 退货/换货信息
	 * @author chenluqiang
	 * @date 2018年12月15日 上午11:22:05 
	 * @param user 该用户信息
	 * @param json 退货/退款信息 json格式
	 * @return 
	 * @throws Exception 
	 */
	@Override
	public Map<String, Object> addRefund(User user, String json) throws Exception {
		//校验json
		if(StringUtils.isBlank(json)) {
			return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_NULL,"json isnull~");
		}
		
		Map<String,Object> jsonMap = JSON.parseObject(json);
		
		//校验map内容
		if(jsonMap==null||jsonMap.isEmpty()
				||jsonMap.get("refund")==null||jsonMap.get("refundItem")==null
				||StringUtils.isBlank(jsonMap.get("refund").toString())
				||StringUtils.isBlank(jsonMap.get("refundItem").toString())) {
			return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_NULL,"json item isnull~");
		}
		
		//设置退货/换货信息
		Refund refund = JSON.parseObject(jsonMap.get("refund").toString(),Refund.class);
		//检查信息
		Map<String,Object> check = this.checkRefund(refund);
		if(check!=null) {
			return check;
		}
		//多个订单 商品item,用List 接收
		@SuppressWarnings("rawtypes")
		List<Map> refundItems = JSON.parseArray(jsonMap.get("refundItem").toString(),Map.class);
		//检查信息
		check = this.checkRefundItem(refundItems);
		if(check!=null) {
			return check;
		}
		//插入退货信息表数据
		check = this.insertRefundDate(refund,user, refundItems);
		if(check!=null) {
			return check;
		}
		//插入退货物流表数据
		this.insertRefundShippingDate(refund,user);
		//插入退货商品信息表数据
		this.insertRefundItemDate(refundItems,refund);
		//插入图片表
		if(jsonMap.get("picIds")!=null&&StringUtils.isNotBlank(jsonMap.get("picIds").toString())) {
			//分割图片id
			List<String> picIds = JSON.parseArray(jsonMap.get("picIds").toString(),String.class);
			for(String picId : picIds) {
				FileInfo fileInfo = fileInfoMapper.selectByPrimaryKey(picId);
				if(fileInfo!=null) {
					//保存图片路径
					Pic pic = new Pic();
					pic.setTitle("退货/换货的物品照片");
					pic.setUrl(fileInfo.getPath());
					pic.setCreateTime(new Date());
					pic.setUpdateTime(new Date());
					picMapper.insertSelective(pic);
				
					//保存图片关联
					RefundPicKey refundPicKey = new RefundPicKey();
					refundPicKey.setPicid(pic.getId());
					refundPicKey.setRefundid(refund.getId());
					refundPicKeyMapper.insertSelective(refundPicKey);
					
					//删除上传临时表
					ZeroHourFile file = new ZeroHourFile();
					file.setFileInfoId(fileInfo.getId());
					zeroHourFileMapper.delete(file);
				}
			}
		}
		
		//插入售后角色层级表
		this.insertRefundLevel(user,refund);
		// 修改process表的refuntType
		String orderId = refund.getOrderid();
		if (StringUtils.isNotBlank(orderId)) {
			Map<String, Object> map = processMapper.findProcessByOrderId(orderId);
			if (map != null && !map.isEmpty()) {
				Process process = new Process();
				process.setId((String) map.get("processId"));
				process.setIsRefund(0);// 是否能申请售后 0=否 1=是
				process.setIsgrants(1); //冻结发放补助金
				process.setUpdateTime(new Date());
				processMapper.updateByPrimaryKeySelective(process);
			}
		}
		
		ORoleLevel oRoleLevel = new ORoleLevel();
		oRoleLevel.setOrderid(orderId);
		oRoleLevel = oRoleLevelMapper.selectOne(oRoleLevel);
		if(oRoleLevel!=null){
			if(StringUtils.isNotBlank(oRoleLevel.getTraderid())){
//				消息推送给分销商
				User Trader = userMapper.selectByPrimaryKey(oRoleLevel.getTraderid());
				JpushClientUtil.initJPushClient(ResultMessage.JGTSKEY, ResultMessage.JGTSECRET);
				if(Trader!=null&&StringUtils.isNoneBlank(Trader.getRegistrationId())) {
					JpushClientUtil.sendToRegistrationId(Trader.getRegistrationId(), "售后通知", "售后通知", "您有新的售后信息！", "", "", "", new HashMap<>());
				}
			}else if(StringUtils.isNotBlank(oRoleLevel.getAgentid())){
//				消息推送给代理商
				User Agent = userMapper.selectByPrimaryKey(oRoleLevel.getAgentid());
				JpushClientUtil.initJPushClient(ResultMessage.JGTSKEY, ResultMessage.JGTSECRET);
				if(Agent!=null&&StringUtils.isNoneBlank(Agent.getRegistrationId())) {
					JpushClientUtil.sendToRegistrationId(Agent.getRegistrationId(), "售后通知", "售后通知", "您有新的售后信息！", "", "", "", new HashMap<>());
				}
			}
		}
		return ResponseUtil.ajaxCheckSuccess(ResultMessage.OK);
	}
	
	/**
	 * 插入退货物流表数据
	 * @author wujunyuan
	 * @date 2018年12月29日  上午10:31:31
	 * @param refund
	 * @param user
	 */
	private void insertRefundShippingDate(Refund refund, User user) {
		RefundShipping refundShipping = new RefundShipping();
		refundShipping.setId(UUID.randomUUID().toString().replace("-", ""));
		refundShipping.setCreateTime(new Date());
		refundShipping.setUpdateTime(new Date());
		String orderId = refund.getOrderid();
		if(StringUtils.isNotBlank(orderId)) {
			//根据orderId获取退货/换货地址信息
			Map<String,Object> orderMap = orderMapper.findOrderAddressById(orderId);
			if(orderMap!=null&&!orderMap.isEmpty()) {
				refundShipping.setAddress(
						(orderMap.get("address"))!=null?orderMap.get("address").toString():null);
				refundShipping.setAddressee(
						(orderMap.get("addressee"))!=null?orderMap.get("addressee").toString():null);
				refundShipping.setAddresseephone(
						(orderMap.get("addresseePhone"))!=null?orderMap.get("addresseePhone").toString():null);
				refundShipping.setElectricname(
						(orderMap.get("electricName"))!=null?orderMap.get("electricName").toString():null);
				refundShipping.setElectricphone(
						(orderMap.get("electricPhone"))!=null?orderMap.get("electricPhone").toString():null);
				refundShipping.setElectricaddress(
						(orderMap.get("electricAddress"))!=null?orderMap.get("electricAddress").toString():null);
				refundShipping.setZipcode(
						(orderMap.get("zipcode"))!=null?orderMap.get("zipcode").toString():null);
				refundShipping.setReceivername(
						(orderMap.get("receiverName"))!=null?orderMap.get("receiverName").toString():null);
			}
		}
		refundShippingMapper.insertSelective(refundShipping);
		//更新refund表ShippingId字段
		refund.setShippingId(refundShipping.getId());
		refund.setUpdateTime(new Date());
		refundMapper.updateByPrimaryKeySelective(refund);
	}

	/**
	 * 插入售后角色层级表
	 * @author chenluqiang
	 * @date 2018年12月17日 下午3:32:21 
	 * @param user
	 * @param refund 
	 */
	private void insertRefundLevel(User user, Refund refund) {
		//设置信息
		SRoleLevel sRoleLevel = new SRoleLevel();
		sRoleLevel.setRefundid(refund.getId());
		
		//查询该用户的层级关系
		URoleLevel uRoleLevel = uRoleLevelMapper.selectByPrimaryKey(user.getId());
		if(user.getType()==3) {//电工
			sRoleLevel.setElectid(user.getId());
			if(uRoleLevel!=null) {
				sRoleLevel.setAgentid(uRoleLevel.getAgentid());
				sRoleLevel.setTraderid(uRoleLevel.getTraderid());
			}
		}else if(user.getType()==2){//分销商
			sRoleLevel.setTraderid(user.getId());
			sRoleLevel.setAgentid(uRoleLevel.getAgentid());
		}else if(user.getType()==1) { //代理商
			sRoleLevel.setAgentid(user.getId());
		}
		
		sRoleLeveLMapper.insertSelective(sRoleLevel);
	}

	/**
	 * 插入退货信息
	 * @author chenluqiang
	 * @date 2018年12月17日 上午11:24:43 
	 * @param refund
	 * @param user
	 * @throws Exception 
	 */
	@SuppressWarnings("unchecked")
	private Map<String,Object> insertRefundDate(Refund refund, User user,@SuppressWarnings("rawtypes") List<Map> refundItems) throws Exception {
		refund.setId(UUID.randomUUID().toString().replaceAll("-", ""));
		//生成退款单号
//		refund.setRefundnum(SnowflakeIdUtil.nextId(9527L, System.currentTimeMillis()) + "");
		//生成售后单号
		String refundNum = this.regexOrderNum
				(refund.getOrdernum(), NumberUtils.getOrderNumber(ResultMessage.REFUND_PREFIX, ResultMessage.REFUND_SUFFIX));
		
		refund.setRefundnum(refundNum);
		//设置用户信息
		refund.setUserid(user.getId());
		refund.setUsername(user.getNickName());
		//设置关联人
		refund.setLinkname(orderMapper.getLinkNameByOrderId(refund.getOrderid()));
		//申请时间
		refund.setApplytime(new Date());
		refund.setCreateTime(new Date());
		refund.setUpdateTime(new Date());
		
		// 设置结算金额
		String totalPrice = "0";
		String agentTotalPrice = "0";
		String traderTotalPrice = "0";
		String totalCount = "0";
		String agentRatio = null;
		String traderRatio = null;
		//遍历插入
		for(Map<String,Object> map : refundItems) {
			//获取商品信息
			OrderItem orderItem = orderItemMapper.selectByPrimaryKey(map.get("ItemId").toString());
			if(orderItem==null) {
				return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_ERROR,"ItemId is error~");
			}

			if(orderItem.getCategoryid()==null) {
				return ResponseUtil.ajaxCheckError(ResultMessage.CATEGORY_ID_ERROR,"categoryId is null~");
			}
			if(StringUtils.isBlank(orderItem.getAgentratio())
					||StringUtils.isBlank(orderItem.getTraderratio())) {
				//获取比例
				CategoryRatio categoryRatio = new CategoryRatio();
				categoryRatio.setCategoryid(orderItem.getCategoryid());
				categoryRatio = categoryRatioMapper.selectOne(categoryRatio);
				if(categoryRatio==null) {
					return ResponseUtil.ajaxCheckError(ResultMessage.CATEGORY_RATIO_ERROR);
				}
				if(StringUtils.isBlank(categoryRatio.getTraderratio())
						||StringUtils.isBlank(categoryRatio.getAgentratio())) {
					return ResponseUtil.ajaxCheckError(ResultMessage.CATEGORY_RATIO_ERROR);
				}
				agentRatio = categoryRatio.getAgentratio();
				traderRatio = categoryRatio.getTraderratio();
				//
				orderItem.setAgentratio(agentRatio);
				orderItem.setTraderratio(traderRatio);
				orderItem.setElectricratio(categoryRatio.getElectricratio());
				orderItemMapper.updateByPrimaryKeySelective(orderItem);
			}else {
				agentRatio = orderItem.getAgentratio();
				traderRatio = orderItem.getTraderratio();
			}
			//商品总价=商品数量*商品价格
			if(StringUtils.isNotBlank(orderItem.getGoodscount())
					&&StringUtils.isNotBlank(orderItem.getGoodsprice())) {
				String goodsPrice = MathUtils.multiply(map.get("itemCount").toString(),orderItem.getGoodsprice());
				/*String agentPrice = MathUtils.multiply(agentRatio,goodsPrice);
				String traderPrice = MathUtils.multiply(traderRatio,goodsPrice);*/
				
				agentTotalPrice=MathUtils.add(agentTotalPrice, goodsPrice);
				traderTotalPrice=MathUtils.add(traderTotalPrice, goodsPrice);
				
				totalPrice=MathUtils.add(totalPrice, goodsPrice);
				totalCount=MathUtils.add(map.get("itemCount").toString(), totalCount);
			}
		}
		agentTotalPrice = MathUtils.multiply(agentRatio,agentTotalPrice);
		traderTotalPrice = MathUtils.multiply(traderRatio,traderTotalPrice);
		//减钱
		/*if(StringUtils.isNotBlank(agentTotalPrice)
				&&agentTotalPrice.indexOf(".")!=-1
				&&!agentTotalPrice.substring(agentTotalPrice.indexOf(".")+2).equals("")) {
			//减1分钱
			agentTotalPrice = MathUtils.sub(agentTotalPrice, "0.01");
		}*/
		
		refund.setAgentprice(agentTotalPrice);
		refund.setTraderprice(traderTotalPrice);
		refund.setTotalprice(totalPrice);
		refund.setCount(totalCount);
		
		//状态：售后状态
		if(user.getType()==1) {
			refund.setStatus(7);
		}else if(user.getType()==2){
			refund.setStatus(5);
		}else if(user.getType()==3){
			ORoleLevel oRoleLevel = oRoleLevelMapper.selectByPrimaryKey(refund.getOrderid());
			if(StringUtils.isNoneBlank(oRoleLevel.getElectid()) && StringUtils.isBlank(oRoleLevel.getTraderid()) 
					&& StringUtils.isNoneBlank(oRoleLevel.getAgentid())) { 
				refund.setStatus(5);
			}else {
				refund.setStatus(3);
			}
		}
		
		refundMapper.insertSelective(refund);
		return null;
	}
	
	/**
	 * 生成售后单号
	 * @author chenluqiang
	 * @date 2019年1月17日 下午9:03:56 
	 * @param ordernum 
	 * @param refundNum
	 * @return
	 */
	private String regexOrderNum(String ordernum, String refundNum) {
		//订单号切割
		String orderRegex = ordernum.substring(ordernum.indexOf("A")+1);
		//售后号切割
		String refundRegex = refundNum.substring(0,refundNum.indexOf("A")+1);
		return refundRegex+orderRegex;
	}

	/**
	 * 检查退货/退款信息
	 * @author chenluqiang
	 * @date 2018年12月15日 下午2:27:40 
	 * @param refund
	 * @return
	 */
	private Map<String, Object> checkRefund(Refund refund) {
		if (refund == null) {
			return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_NULL, "refund isnull~");
		}

		// 校验订单id
		if (StringUtils.isBlank(refund.getOrderid())) {
			return ResponseUtil.ajaxCheckError(ResultMessage.ORDERID_ISNULL);
		}
		if (refund.getOrderid().length() != 32) {
			return ResponseUtil.ajaxCheckError(ResultMessage.ORDERID_ISERROR, "orderId length must be equal 32!");
		}
		// 校验订单num
		if (StringUtils.isBlank(refund.getOrdernum())) {
			return ResponseUtil.ajaxCheckError(ResultMessage.ORDERNUM_ISNULL,"ordernum is null~");
		}
		
		//校验订单是否已经提交了申请
		Refund refund2 = new Refund();
		refund2.setOrderid(refund.getOrderid());
		List<Refund> list = refundMapper.select(refund2);
		if(list!=null&&list.size()!=0) {
			return ResponseUtil.ajaxCheckError(ResultMessage.ORDER_HAS_REFUND,"orderId is exits~");
		}
		refund2 = new Refund();
		refund2.setOrdernum(refund.getOrdernum());
		list = refundMapper.select(refund2);
		if(list!=null&&list.size()!=0) {
			return ResponseUtil.ajaxCheckError(ResultMessage.ORDER_HAS_REFUND,"ordernum is exits~");
		}
		// 校验类型
		if (refund.getType() == null || refund.getType() < 0 || refund.getType() > 1) {
			return ResponseUtil.ajaxCheckError(ResultMessage.TYPE_ISERROR);
		}
		// 判断类型
		if (refund.getType() == 0) { // 退货
			// 校验退货总价
			if (StringUtils.isBlank(refund.getTotalprice())) {
				return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_NULL, "total price isnull~");
			}
		}
		// 校验换货/退货总数
		if (StringUtils.isBlank(refund.getCount())) {
			return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_NULL, "count isnull~");
		}
		// 退货原因
		if (StringUtils.isBlank(refund.getReason())) {
			return ResponseUtil.ajaxCheckError(ResultMessage.PLESE_SELECT_REASON, "reason isnull~");
		}
		return null;
	}
	
	/**
	 * 插入退货/换货 商品数据
	 * @author chenluqiang
	 * @date 2018年12月18日 下午3:51:31 
	 * @param refundItems
	 * @param refund
	 */
	@SuppressWarnings("unchecked")
	private void insertRefundItemDate(@SuppressWarnings("rawtypes") List<Map> refundItems, Refund refund) {
		//遍历插入
		for(Map<String,Object> map : refundItems) {
			//获取商品信息
			OrderItem orderItem = orderItemMapper.selectByPrimaryKey(map.get("ItemId").toString());
			//设置信息
			RefundItem refundItem = new RefundItem();
			refundItem.setRefundid(refund.getId());
			refundItem.setGoodscount(map.get("itemCount").toString());
			//设置分类id
			refundItem.setCategoryid(orderItem.getCategoryid());
			//设置比例
			refundItem.setAgentratio(orderItem.getAgentratio());
			refundItem.setTraderratio(orderItem.getTraderratio());
			refundItem.setElectricratio(orderItem.getElectricratio());
			//设置商品信息
			refundItem.setGoodsid(orderItem.getGoodsid());
			refundItem.setGoodstitle(orderItem.getGoodstitle());
			refundItem.setGoodspic(orderItem.getGoodspic());
			refundItem.setGoodsprice(orderItem.getGoodsprice());
			
			refundItem.setCreateTime(new Date());
			refundItem.setUpdateTime(new Date());
			refundItemMapper.insertSelective(refundItem);
		}
	}
	/**
	 * 校验退货 的商品信息
	 * @author chenluqiang
	 * @date 2018年12月15日 下午4:03:06 
	 * @param refundItem
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private Map<String, Object> checkRefundItem(@SuppressWarnings("rawtypes") List<Map> refundItem) {
		if(refundItem==null||refundItem.isEmpty()) {
			return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_NULL,"refundItem isnull~");
		}
		
		//遍历校验
		for(Map<String,Object> map : refundItem) {
			//校验订单 商品的id
			if(map.get("ItemId")==null||StringUtils.isBlank(map.get("ItemId").toString())) {
				return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_NULL,"ItemId isnull~");
			}
			Integer num = orderItemMapper.isExitsByOrderItemId(map.get("ItemId").toString());
			if(num==null||num!=1) {
				return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_ERROR,"itemId is error~");
			}
			//校验退货订单 商品的数量
			if(map.get("itemCount")==null||StringUtils.isBlank(map.get("itemCount").toString())) {
				return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_NULL,"itemCount isnull~");
			}
		}
		return null;
	}

	
	/**
	 * 售后列表
	 * @author chenluqiang
	 * @date 2018年12月17日 下午2:42:37 
	 * @param type 类型 0=我的售后审核 1=我的售后申请 2=已完成
	 * @return
	 */
	@Override
	public Map<String, Object> refundList(User user,Long pageStart,Long pageTotal,Integer type) {
		//校验
		if(type==null||type<0||type>2) {
			return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_ERROR,"type is error~");
		}
		
		//初始化分页参数
		pageStart = PageUtils.initialPageStart(pageStart);
		pageTotal = PageUtils.packagePageTotal(pageTotal, 5, 10);
		//sql分页中的起始值
		Long countPageStart = PageUtils.countPageStart(pageStart, pageTotal);
		
		//获取数据列表
		List<Map<String,Object>> data = refundMapper.getRefundListByStatus(user.getId(),type,countPageStart,pageTotal,user.getType());
		Long count = refundMapper.getRefundListCountByStatus(user.getId(), type,user.getType());
		
		//订单是否已审核(已处理)
		int isAuditingFinish = 0;
		
		//设置返回的状态文字
		if(data!=null&&!data.isEmpty()) {
			for(Map<String,Object> map:data) {
				int status = (int) map.get("status");   //售后状态
				int refundType = (int) map.get("type");  //售后类型： 0=退货 1=换货

				if(refundType==0 && status!=12){
					map.put("code", "0"); //退货-处理中
					map.put("status", "退货-处理中"); 
				}
				else if(refundType==1 && status!=12){
					map.put("code", "1"); //换货-处理中
					map.put("status", "换货-处理中"); 
				}
				
				if(refundType==0 &&status==12) {
					map.put("code", "2"); //退货-已完成
					map.put("status", "退货-已完成"); 
				}
				
				if(refundType==1 && status==12){
					map.put("code", "3"); //换货-已完成
					map.put("status", "换货-已完成"); 
				}
				/*退货-申请未通过*/
				 if(refundType==0 && (status==4||status==6||status==8)){
					map.put("code", "4"); 
					map.put("status", "退货-申请未通过"); 
				}
				 if(refundType==1 && (status==4||status==6||status==8)){
					map.put("code","5"); 
					map.put("status", "换货-申请未通过"); 
				}
				map.remove("type");
				
				if(user.getType()==2) { //分销商
					if(status!=3) {
						isAuditingFinish = 1; //已审核(已处理)
					}
				}else if(user.getType()==1) { //代理商
					if(status>=6) {
						isAuditingFinish = 1; //已审核(已处理)
					}
				}else if(user.getType()==3){
					if(status==12)
						isAuditingFinish = 1;
				}
				map.put("isAuditingFinish", isAuditingFinish);
			}
		}
		
		return ResponseUtil.ajaxCheckSuccess(ResultMessage.OK,new PageResponse(pageStart, pageTotal,count, data));
	}
	
	/**
	 * 删除售后数据
	 * @author chenluqiang
	 * @date 2018年12月18日 上午9:30:36 
	 * @param refundId 售后id
	 * @return
	 */
	@Override
	public Map<String, Object> delRefund(User user, String refundId) {
		//校验refundId
		if(StringUtils.isBlank(refundId)) {
			return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_NULL,"refundId isnull~");
		}
		
		//删除售后
		refundMapper.deleteByPrimaryKey(refundId);
		
		//删除售后item
		RefundItem refundItem = new RefundItem();
		refundItem.setRefundid(refundId);
		refundItemMapper.delete(refundItem);
		
		//删除售后图片
		RefundPicKey refundPicKey = refundPicKeyMapper.selectByPrimaryKey(refundId);
		if(refundPicKey!=null) {
			picMapper.deleteByPrimaryKey(refundPicKey.getPicid());
		}
		refundPicKeyMapper.deleteByPrimaryKey(refundId);
		
		return ResponseUtil.ajaxCheckSuccess(ResultMessage.OK);
	}

	

	/**
	 * 售后详情
	 * @author chenluqiang
	 * @date 2018年12月18日 上午11:16:15 
	 * @param request
	 * @param refundId 售后id
	 * @return
	 * @throws Exception
	 */
	@Override
	public Map<String, Object> refundDetail(User user, String refundId) {
		//校验refundId
		if(StringUtils.isBlank(refundId)) {
			return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_NULL,"refundId isnull~");
		}
		
		Map<String,Object> result = new HashMap<String,Object>();
		//查询数据
		Map<String,Object> refundMap =  refundMapper.getRefundDetail(refundId);
		List<Map<String,Object>> refundItems = refundItemMapper.getRefundItemByRefundId(refundId);
		//图片
		List<Map<String,Object>> refundPics =  picMapper.getRefundPics(refundId);
		
		//图片处理
		this.handleListPics(refundItems,"goodsPic");
		this.handleListPics(refundPics,"url");
		
		//流程
		List<Map<String,Object>> processList = new ArrayList<>();
		
		Map<String,Object> map1 = new HashMap<>();
		map1.put("name", "申请");
		map1.put("title", "电工");
		map1.put("status", "0");  //status   0=白色   1=绿色  2=灰色  3=红色(已拒绝) 4=红色(完成) 
		
		Map<String,Object> map2 = new HashMap<>();
		map2.put("name", "审核");
		map2.put("title", "分销");
		map2.put("status", "0");
		
		Map<String,Object> map3 = new HashMap<>();
		map3.put("name", "审核");
		map3.put("title", "代理");
		map3.put("status", "0");
		
		Map<String,Object> map4 = new HashMap<>();
		map4.put("name", "批准");
		map4.put("title", "厂家");
		map4.put("status", "0");
		
		Map<String,Object> map5 = new HashMap<>();
		map5.put("name", "退货");
		map5.put("title", "分销");
		map5.put("status", "0");
		
		Map<String,Object> map6 = new HashMap<>();
		map6.put("name", "收货");
		map6.put("title", "厂家");
		map6.put("status", "0");
		
		Map<String,Object> map7 = new HashMap<>();
		map7.put("name", "退款");
		map7.put("title", "厂家");
		map7.put("status", "0");
		
		Map<String,Object> map8 = new HashMap<>();
		map8.put("name", "完成");
		map8.put("title", "");
		map8.put("status", "0");
		
		processList.add(map1);
		processList.add(map2);
		processList.add(map3);
		processList.add(map4);
		processList.add(map5);
		processList.add(map6);
		processList.add(map7);
		processList.add(map8);
		
		//获取订单流程状态
		int status = (int) refundMap.get("status");
		//获取申请售后的用户
		String userId = (String) refundMap.get("userId");
		User orderUser = userMapper.selectByPrimaryKey(userId);
		//获取售后类型   0=退货  1=换货
		int refundType = (int) refundMap.get("type");
		//订单是否完成  0=否  1=是
		int isFinish = 0;
		//订单是否需要访问该接口的用户审核 0=不需要 1=需要
		int isAuditing = 0;
		
		
		int type = 0;
		SRoleLevel sRoleLevel = sRoleLeveLMapper.selectByPrimaryKey(refundId);
		if(StringUtils.isNoneBlank(sRoleLevel.getElectid()) && StringUtils.isBlank(sRoleLevel.getTraderid()) 
				&& StringUtils.isNoneBlank(sRoleLevel.getAgentid())) { 
			type = 1;  //若分销商为空,电工和代理商id不为空,说明电工的直接上级是代理商
		}
		
		//若售后类型为换货
		if(refundType==1) {
			map7.put("name", "换货");
			map5.put("name", "换货");
		}
		
		//正常流程
		if(status==3) {  //分销商待审核状态
			map2.put("status", "1");  //绿色
		}else if(status==4) {  //分销商拒绝
			map2.put("name", "已拒绝");
			map2.put("status", "3");  // 红色(已拒绝)
			map7.put("status", "4");  // 红色(完成)
			isFinish = 1;
		}else if(status==5) { //代理商待审核
			map2.put("status", "2");  //灰色
			map3.put("status", "1");  //绿色
		}else if(status==6) { //代理商拒绝
			map2.put("status", "2");  //灰色
			map3.put("name", "已拒绝");
			map3.put("status", "3");  // 红色(已拒绝)
			map7.put("status", "4");  // 红色(完成)
			isFinish = 1;
		}else if(status==7) { //厂家待批准
			map2.put("status", "2");  //灰色
			map3.put("status", "2");  //灰色
			map4.put("status", "1");  //绿色
		}else if(status==8) { //厂家拒绝
			map2.put("status", "2");  //灰色
			map3.put("status", "2");  //灰色
			map4.put("name", "已拒绝");
			map4.put("status", "3");  // 红色(已拒绝)
			map7.put("status", "4");  // 红色(完成)
			isFinish = 1;
		}else if(status==9) {  //请退货
			map2.put("status", "2");  //灰色
			map3.put("status", "2");  //灰色
			map4.put("status", "2");  //灰色
			map5.put("status", "1");  //绿色
		}else if(status==10) {  //厂家收到货
			map2.put("status", "2");  //灰色
			map3.put("status", "2");  //灰色
			map4.put("status", "2");  //灰色
			map5.put("status", "2");  //灰色
			map6.put("status", "1");  //绿色
		}else if(status==11) {  //厂家退款或换货
			map2.put("status", "2");  //灰色
			map3.put("status", "2");  //灰色
			map4.put("status", "2");  //灰色
			map5.put("status", "2");  //灰色
			map6.put("status", "2");  //灰色
			map7.put("status", "1");  // 绿色
		}else if(status==12) {
			map2.put("status", "2");  //灰色
			map3.put("status", "2");  //灰色
			map4.put("status", "2");  //灰色
			map5.put("status", "2");  //灰色
			map6.put("status", "2");  //灰色
			map7.put("status", "2");  //灰色
			map8.put("status", "4");  // 红色(完成)
			isFinish = 1;  //订单已完成
		}
		
		//判断申请售后的用户类型
		if(orderUser.getType()==3) {  //电工申请的售后
			map1.put("status", "2");  //灰色
			if(type==1) {
				processList.remove(map2); //电工的直接上级是代理商,移除分销商模块
			}
		}else if(orderUser.getType()==2) { //分销商申请的售后
			processList.remove(map1);  //移除掉电工模块
			map2.put("name", "提交");  //分销商提交
		}else if(orderUser.getType()==1) { //代理商申请的售后
			processList.remove(map1);  //移除掉电工模块
			processList.remove(map2);  //移除掉分销商模块
			map3.put("name", "提交");  //代理商提交
			map5.put("title", "代理");    //代理退货
		}
		
		//判断访问接口的用户类型
		if(user.getType()==3) { //电工
			
			//去除分销商,代理商价格
			refundMap.remove("agentPrice");
			refundMap.remove("traderPrice");
			
		}else if(user.getType()==2) { //分销商
			
			//去除代理商价格
			refundMap.remove("agentPrice");
			
			//若访问该接口的用户是分销商，且售后状态为分销商待审核状态
			if(status==3) {
				isAuditing = 1;  //需要该用户审核
			}
			
		}else if(user.getType()==1) { //代理商
			
			//去除分销商价格
			refundMap.remove("traderPrice");
			
			//若访问该接口的用户是代理商，且售后状态为代理商待审核状态
			if(status==5) {
				isAuditing = 1;//需要该用户审核
			}
			
		}
		//设置返回信息
		result.put("refund",refundMap);
		result.put("refundItem", refundItems);
		result.put("pics", refundPics);
		result.put("process", processList);
		result.put("isFinish", isFinish);
		result.put("userType", user.getType());  //返回用户类型   3=电工  2=分销商  1=代理商
		result.put("isAuditing", isAuditing);
		
		//设置格式
		Map<String, Object> check = this.settingSettlementMoney(result,refundItems);
		if(check!=null) {
			return check;
		}
		return ResponseUtil.ajaxCheckSuccess(ResultMessage.OK,result);
	}
	
	/**
	 * 整理商品信息 格式。
	 * @author chenluqiang
	 * @date 2019年1月19日 上午9:50:38 
	 * @param result
	 * @param orderItemList
	 * @return
	 */
	private Map<String, Object> settingSettlementMoney(Map<String, Object> resultMap,
			List<Map<String, Object>> goodsList) {
		
		Map<String,Map<String,Object>> allMap = new HashMap<String,Map<String,Object>>();
		//
		if(goodsList!=null&&!goodsList.isEmpty()) {
			for (Map<String, Object> map : goodsList) {
				//map
				if(map.get("categoryId")==null||StringUtils.isBlank(map.get("categoryId").toString())){
					return ResponseUtil.ajaxCheckError(ResultMessage.THIS_GOODS_NOT_CATEGORY,"categoryId is null~");
				}	
				//小类
				Map<String,Object> categoryMap =categoryMapper.getCategoryByCategoryId
							(Integer.parseInt(map.get("categoryId").toString()));

				if(categoryMap==null||categoryMap.isEmpty()||
						categoryMap.get("parentName")==null || StringUtils.isBlank(categoryMap.get("parentName").toString())) {
					return ResponseUtil.ajaxCheckError(ResultMessage.THIS_GOODS_NOT_LARGECATEGORY,"categoryMap is null~");
				}
				//拼接
				StringBuffer sb = new StringBuffer();
				sb.append(categoryMap.get("parentName").toString());
				sb.append("-");
				sb.append(categoryMap.get("categoryName").toString());
				
				categoryMap.put("nCategoryName", sb.toString());
				
				allMap.put(sb.toString(),categoryMap);
				
			}
			
			//整理返回格式
			for(Map<String,Object> categoryMap:allMap.values()) {
				List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
				for (Map<String, Object> map : goodsList) {
					if(categoryMap.get("categoryId").toString().equals(map.get("categoryId").toString())) {
						list.add(map);
					}
				}
				categoryMap.put("goods",list);
				//小计金额
				String minMoney = "0";
				//型号
				String number = "0";
				
				for(Map<String,Object> map :list) {
					String goodsPrice = MathUtils.multiply(map.get("goodsCount").toString(), map.get("goodsPrice").toString());
					minMoney = MathUtils.add(minMoney, goodsPrice);
					number = MathUtils.add("1", number);
				}
				categoryMap.put("minMoney",minMoney);
				categoryMap.put("number",number);
				
				categoryMap.remove("parentName");
				categoryMap.remove("categoryName");
			}
			
			
			resultMap.put("categorys", allMap.values());//
		}
		return null;
	}
	
	/**
	 * list图片处理
	 * @author chenluqiang
	 * @date 2018年12月18日 下午4:01:53 
	 * @param code key值
	 * @param list
	 */
	private void handleListPics(List<Map<String,Object>> list,String code) {
		//遍历处理
		if(list!=null&&!list.isEmpty()) {
			for(Map<String,Object> map : list) {
				if(map.get(code)!=null&&StringUtils.isNotBlank(map.get(code).toString())) {
					map.put(code, this.getPic(map.get(code).toString()));
				}
			}
		}
	}
	
	/**
	 * 拼接图片域名
	 * @author gujiahua
	 * 2018年11月28日 上午11:28:03
	 * @param pic
	 * @return
	 */
	private String getPic(String pic){
		if(!CheckUtil.checkUrl(pic)){
			pic =  fastdfsUrl+pic;
		}
		return pic;
	}

	/**
	 * 根据文章类型获取文章
	 * @author wujunyuan
	 * @date 2018年12月26日  上午10:30:52
	 * @param request
	 * @param type 1=关于狮盾 2=售后说明  4=用户协议
	 * @return
	 */
	@Override
	public Map<String, Object> getArticle(Integer type) {
		//校验参数
		if(type==null) {
			return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_ERROR,"type error");
		}

		// 根据文章类型获取文章
		List<Map<String, Object>> result = articleMapper.getArticleByType(type);
		// 处理图片
		if (result != null && !result.isEmpty()) {
			for (Map<String, Object> map : result) {
				if (map.get("picture") != null && StringUtils.isNotBlank(map.get("picture").toString())) {
					map.put("picture", this.getPic(map.get("picture").toString()));
				}
			}
		}
		return ResponseUtil.ajaxCheckSuccess(ResultMessage.OK, result);
	}

	/**
	 * 获取(退货/换货)原因
	 * @author wujunyuan
	 * @date 2018年12月27日  下午5:48:42
	 * @param status 0=退货原因 1=换货原因
	 * @return
	 */
	@Override
	public Map<String, Object> getReason(Integer status) {
		//校验参数
		if(status==null||status<0||status>1) {
			return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_ERROR,"status error");
		}
		//获取(退货/换货)原因
		List<Map<String,Object>> result = refundMapper.findReason(status);
		
		return ResponseUtil.ajaxCheckSuccess(ResultMessage.OK, result);
	}

	/**
	 * 审核售后
	 *
	 * @author lihongwu
	 * 2018年12月29日 上午11:33:39
	 * @param request
	 * @param refundId
	 * @param type   0=拒绝  1=通过
	 * @return
	 * @throws Exception
	 */
	@Override
	public Map<String, Object> auditing(User user, String refundId, Integer type,String content) {
		
		Map<String,Object> check = checkAuditingParam(user,refundId,type,content);
		if(check!=null) {
			return check;
		}
		
		//售后
		Refund refund = refundMapper.selectByPrimaryKey(refundId);
		//获取订单关联用户
		String orderId = refund.getOrderid();
		ORoleLevel oRoleLevel = new ORoleLevel();
		oRoleLevel.setOrderid(orderId);
		oRoleLevel = oRoleLevelMapper.selectOne(oRoleLevel);
		//售后状态
		int status = refund.getStatus();
		
		//审核用户为分销商且售后状态为分销商待审核
		if(user.getType()==2 && status==3) {
			if(type==0) {
				refund.setStatus(4);  //分销商拒绝状态
				if(oRoleLevel!=null && StringUtils.isNotBlank(oRoleLevel.getElectid())){
//					消息推送给电工
					User Elect = userMapper.selectByPrimaryKey(oRoleLevel.getElectid());
					JpushClientUtil.initJPushClient(ResultMessage.JGTSKEY, ResultMessage.JGTSECRET);
					if(Elect!=null&&StringUtils.isNoneBlank(Elect.getRegistrationId())) {
						JpushClientUtil.sendToRegistrationId(Elect.getRegistrationId(), "售后通知", "售后通知", "分销商拒绝了您提交的售后信息!", "", "", "", new HashMap<>());
					}
				}
			}else if(type ==1) {
				refund.setStatus(5);  //代理商待审核状态
				if(oRoleLevel!=null && StringUtils.isNotBlank(oRoleLevel.getAgentid())){
//					消息推送给代理商
					User Agent = userMapper.selectByPrimaryKey(oRoleLevel.getAgentid());
					JpushClientUtil.initJPushClient(ResultMessage.JGTSKEY, ResultMessage.JGTSECRET);
					if(Agent!=null&&StringUtils.isNoneBlank(Agent.getRegistrationId())) {
						JpushClientUtil.sendToRegistrationId(Agent.getRegistrationId(), "售后通知", "售后通知", "您有新的售后信息!", "", "", "", new HashMap<>());
					}
				}
				if(oRoleLevel!=null && StringUtils.isNotBlank(oRoleLevel.getElectid())){
//					消息推送给电工
					User Elect = userMapper.selectByPrimaryKey(oRoleLevel.getElectid());
					JpushClientUtil.initJPushClient(ResultMessage.JGTSKEY, ResultMessage.JGTSECRET);
					if(Elect!=null&&StringUtils.isNoneBlank(Elect.getRegistrationId())) {
						JpushClientUtil.sendToRegistrationId(Elect.getRegistrationId(), "售后通知", "售后通知", "分销商同意了您提交的售后信息!", "", "", "", new HashMap<>());
					}
				}
			}
		}
		//审核用户为代理商且售后状态为代理商待审核
		if(user.getType()==1 && status==5) {
			if(type==0) {
				refund.setStatus(6);  //代理商拒绝状态
				
				if(oRoleLevel!=null && StringUtils.isNotBlank(oRoleLevel.getElectid())){
//					消息推送给电工
					User Elect = userMapper.selectByPrimaryKey(oRoleLevel.getElectid());
					JpushClientUtil.initJPushClient(ResultMessage.JGTSKEY, ResultMessage.JGTSECRET);
					if(Elect!=null&&StringUtils.isNoneBlank(Elect.getRegistrationId())) {
						JpushClientUtil.sendToRegistrationId(Elect.getRegistrationId(), "售后通知", "售后通知", "代理商拒绝了您提交的售后信息!", "", "", "", new HashMap<>());
					}
				}
				if(oRoleLevel!=null && StringUtils.isNotBlank(oRoleLevel.getTraderid())){
//					消息推送给分销商
					User Trader = userMapper.selectByPrimaryKey(oRoleLevel.getTraderid());
					JpushClientUtil.initJPushClient(ResultMessage.JGTSKEY, ResultMessage.JGTSECRET);
					if(Trader!=null&&StringUtils.isNoneBlank(Trader.getRegistrationId())) {
						JpushClientUtil.sendToRegistrationId(Trader.getRegistrationId(), "售后通知", "售后通知", "代理商拒绝了电工提交的售后信息!", "", "", "", new HashMap<>());
					}
				}
			}else if(type ==1) {
				refund.setStatus(7);  //厂家待批准状态
				
				if(oRoleLevel!=null && StringUtils.isNotBlank(oRoleLevel.getElectid())){
//					消息推送给电工
					User Elect = userMapper.selectByPrimaryKey(oRoleLevel.getElectid());
					JpushClientUtil.initJPushClient(ResultMessage.JGTSKEY, ResultMessage.JGTSECRET);
					if(Elect!=null&&StringUtils.isNoneBlank(Elect.getRegistrationId())) {
						JpushClientUtil.sendToRegistrationId(Elect.getRegistrationId(), "售后通知", "售后通知", "代理商同意了您提交的售后信息!", "", "", "", new HashMap<>());
					}
				}
				if(oRoleLevel!=null && StringUtils.isNotBlank(oRoleLevel.getTraderid())){
//					消息推送给分销商
					User Trader = userMapper.selectByPrimaryKey(oRoleLevel.getTraderid());
					JpushClientUtil.initJPushClient(ResultMessage.JGTSKEY, ResultMessage.JGTSECRET);
					if(Trader!=null&&StringUtils.isNoneBlank(Trader.getRegistrationId())) {
						JpushClientUtil.sendToRegistrationId(Trader.getRegistrationId(), "售后通知", "售后通知", "代理商同意了电工提交的售后信息!", "", "", "", new HashMap<>());
					}
				}
			}
		}
		refund.setCause(content);
		refundMapper.updateByPrimaryKeySelective(refund);
		return ResponseUtil.ajaxCheckSuccess(ResultMessage.OK);
	}

	/**
	 * 校验审核售后参数
	 *
	 * @author lihongwu
	 * 2018年12月29日 上午11:33:39
	 * @param request
	 * @param refundId
	 * @param type   0=拒绝  1=通过
	 * @return
	 * @throws Exception
	 */
	private Map<String, Object> checkAuditingParam(User user, String refundId, Integer type,String content) {
		if(type==null) {
			return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_ERROR, "type is null");
		}
		if(type<0 || type>1) {
			return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_ERROR, "type is error");
		}
		
		if(type==0 && StringUtils.isBlank(content)) {
			return ResponseUtil.ajaxCheckError(ResultMessage.REFUND_REASON_IS_NULL);
		}
		if(type==0 && content.length()>150) {
			return ResponseUtil.ajaxCheckError(ResultMessage.REFUND_REASON_IS_TOO_LONG);
		}
		if(StringUtils.isBlank(refundId)) {
			return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_ERROR, "refundId is null");
		}
		
		Refund refund = refundMapper.selectByPrimaryKey(refundId);
		if(refund==null) {
			return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_ERROR, "refundId is error");
		}
		//提交售后的用户
		User refundUser = userMapper.selectByPrimaryKey(refund.getUserid());
		//售后状态
		int status = refund.getStatus();
		//若审核用户和提交售后的用户是同级
		if(user.getType()==refundUser.getType()) {
			return ResponseUtil.ajaxCheckError(ResultMessage.SYSTEM_ERROR, "userType is error");
		}
		//若审核用户的类型不是代理商且不是分销商
		if(user.getType()!=1 && user.getType()!=2) {
			return ResponseUtil.ajaxCheckError(ResultMessage.SYSTEM_ERROR, "userType is error");
		}
		//若审核用户是分销商且提交售后的用户不是电工
		if(user.getType()==2 && refundUser.getType()!=3) {
			return ResponseUtil.ajaxCheckError(ResultMessage.SYSTEM_ERROR, "userType is error");
		}
		//若审核用户是分销商且售后状态不为3(分销商待审核)
		if(user.getType()==2 && status!=3) {
			return ResponseUtil.ajaxCheckError(ResultMessage.SYSTEM_ERROR, "refund status or userType is error");
		}
		//若审核用户是代理商且售后状态不为5(代理商待审核)
		if(user.getType()==1 && status!=5) {
			return ResponseUtil.ajaxCheckError(ResultMessage.SYSTEM_ERROR, "refund status or userType is error");
		}
		return null;
	}
	
	/**
	 * 获取售后申请 结算金额 ，退货总价
	 * @author chenluqiang
	 * @date 2019年1月16日 下午4:33:27 
	 * @param request
	 * @param goodsJson 商品数量 与价额信息
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings({ "rawtypes", "unchecked"})
	@Override
	public Map<String, Object> getRefundMoney(User user, String goodsJson) {
		
		//数据校验
		if(StringUtils.isBlank(goodsJson)) {
			return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_NULL,"goodsJson is null~");
		}
		//设置返回值
		Map<String,Object> result = new HashMap<>();
		//转map
		List<Map> list = JSON.parseArray(goodsJson,Map.class);
		//退货总价
		String totalPrice= "0";
		//结算总价
		String paymentPrice = null;
		//产品总数
		String totalCount="0";
		//代理商总结算价
		String agentTotalPrice ="0";
		//分销商总结算价
		String traderTotalPrice="0";
		
		for(Map<String,Object> map : list) {
			//校验orderItemId
			if(map.get("orderItemId")==null||StringUtils.isBlank(map.get("orderItemId").toString())) {
				return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_ERROR,"orderItemId is error~");
			}
			//校验categoryId
			if(map.get("categoryId")==null||StringUtils.isBlank(map.get("categoryId").toString())) {
				return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_ERROR,"categoryId is error~");
			}
			//校验商品价格
			if(StringUtils.isBlank((String)map.get("goodsPrice"))) {
				return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_NULL,"goodsPrice is null~");
			}
			//校验商品数量
			if(map.get("goodsCount")==null||StringUtils.isBlank(map.get("goodsCount").toString())) {
				return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_NULL,"goodsCount is null~");
			}
			
			//获取下单时的比例
			OrderItem orderItem = orderItemMapper.selectByPrimaryKey(map.get("orderItemId").toString());
			if(orderItem==null) {
				return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_ERROR,"orderItemId is error~");
			}
			String agentRatio = null;
			String traderRatio = null;

			if(orderItem.getCategoryid()==null) {
				return ResponseUtil.ajaxCheckError(ResultMessage.CATEGORY_ID_ERROR,"categoryId is null~");
			}
			if(StringUtils.isBlank(orderItem.getAgentratio())
					||StringUtils.isBlank(orderItem.getTraderratio())) {
				//获取比例
				CategoryRatio categoryRatio = new CategoryRatio();
				categoryRatio.setCategoryid(orderItem.getCategoryid());
				categoryRatio = categoryRatioMapper.selectOne(categoryRatio);
				if(categoryRatio==null) {
					return ResponseUtil.ajaxCheckError(ResultMessage.CATEGORY_RATIO_ERROR);
				}
				if(StringUtils.isBlank(categoryRatio.getTraderratio())
						||StringUtils.isBlank(categoryRatio.getAgentratio())) {
					return ResponseUtil.ajaxCheckError(ResultMessage.CATEGORY_RATIO_ERROR);
				}
				agentRatio = categoryRatio.getAgentratio();
				traderRatio = categoryRatio.getTraderratio();
				//
				orderItem.setAgentratio(agentRatio);
				orderItem.setTraderratio(traderRatio);
				orderItem.setElectricratio(categoryRatio.getElectricratio());
				orderItemMapper.updateByPrimaryKeySelective(orderItem);
			}else {
				agentRatio = orderItem.getAgentratio();
				traderRatio = orderItem.getTraderratio();
			}
			//商品总价=商品数量*商品价格
			if(map.get("goodsCount")!=null&&StringUtils.isNotBlank(map.get("goodsCount").toString())
					&&map.get("goodsPrice")!=null
					&&StringUtils.isNotBlank(map.get("goodsPrice").toString())) {
				
				String goodsPrice = MathUtils.multiply(map.get("goodsCount").toString(), map.get("goodsPrice").toString());
				String agentPrice = MathUtils.multiply(agentRatio,goodsPrice);
				String traderPrice = MathUtils.multiply(traderRatio,goodsPrice);
				
				agentTotalPrice=MathUtils.add(agentTotalPrice, agentPrice);
				traderTotalPrice=MathUtils.add(traderTotalPrice, traderPrice);
				
				totalPrice=MathUtils.add(totalPrice, goodsPrice);
				totalCount=MathUtils.add(map.get("goodsCount").toString(), totalCount);
			}
		}
		
		Map<String,Object> allMap = new HashMap<>();
		for(Map<String,Object> map3 : list) {
			Map<String,Object> tempMap = new HashMap<>();
			//小计金额
			String minMoney = "0";
			//型号
			String number = "0";
			String categoryId = null;
			for (Map<String, Object> map : list) {
				if(map3.get("categoryId").toString().equals(map.get("categoryId").toString())) {
					String goodsPrice = MathUtils.multiply(map.get("goodsCount").toString(), map.get("goodsPrice").toString());
					minMoney = MathUtils.add(minMoney, goodsPrice);	
					number = MathUtils.add("1", number);
					categoryId = map3.get("categoryId").toString();
				}
			}
			//整理返回格式
			tempMap.put("categoryId",categoryId);
			tempMap.put("minMoney",minMoney);
			tempMap.put("number",number);
			allMap.put(map3.get("categoryId").toString(), tempMap);
		}
		//校验角色
		if(user.getType()==3) {
			//电工
			paymentPrice = totalPrice;
		}else if(user.getType()==2) {
			//分销商
			paymentPrice = traderTotalPrice;
		}else if(user.getType() == 1) {
			//代理商
			paymentPrice = agentTotalPrice;
		}
		result.put("list", allMap.values());
		result.put("totalPrice", totalPrice);
		result.put("paymentPrice", paymentPrice);
		result.put("count", totalCount);
		return ResponseUtil.ajaxCheckSuccess(ResultMessage.OK,result);
	}
	
}
